package com.tyj.movie.controller;


import com.tyj.movie.config.security.UserDetailsPacking;
import com.tyj.movie.constant.AjaxConstant;
import com.tyj.movie.entity.Users;
import com.tyj.movie.service.UsersService;
import com.tyj.movie.util.R;
import com.tyj.movie.util.SecurityUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.stereotype.Controller;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author tyj
 * @since 2021-06-28
 */
@Controller
@RequestMapping("/movie/users")
public class UsersController {

    @Autowired
    UsersService userService;

//    /**
//     * 跳转到错误页面
//     * @return
//     */
//    @PostMapping("/error/loginError")
//    public String goTOLoginErrorPage() {
//        return "/error/loginError";
//    }

    @GetMapping("/login")
    public String goTOLoginPage(){
        return "login";
    }


    /**
     * 判断username是否存在
     *
     * @param username
     * @return
     */
    @ResponseBody
    @RequestMapping("/judgeUsername")
    public R judgeUsername(String username) {
        Users user = userService.judgeUsername(username);
        if (user != null) {
            return R.error(AjaxConstant.AjAX_ACCOUNT_EXISTS.getCode(), AjaxConstant.AjAX_ACCOUNT_EXISTS.getMsg());
        } else {
            return R.ok();
        }
    }

    /**
     * 注册
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public R register(@Valid Users user) {
        //效验
        Users userbool = userService.judgeUsername(user.getUsername());
        if (userbool == null) {
            //可以注册
            userService.register(user.getUsername(), user.getPassword());
            return R.ok();
        } else {
            //不可以注册
            return R.error(AjaxConstant.AjAX_ACCOUNT_EXISTS.getCode(), AjaxConstant.AjAX_ACCOUNT_EXISTS.getMsg());
        }
    }

    /**
     * 修改头像
     * @param headImgUrl 头像路径
     * @return
     */
    @PostMapping("/editHeadImgUrl")
    @ResponseBody
    public R editHeadImgUrl(String headImgUrl, HttpServletRequest request){
        Users users = SecurityUtil.getSessionUser();
        users.setHeadImgUrl(headImgUrl);
        Integer num =userService.editHeadImgUrl(users);

        //修改redisSession中的对象
            //1.从HttpServletRequest中获取SecurityContextImpl对象
            SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
            //2.从SecurityContextImpl中获取Authentication对象
            Authentication authentication = securityContextImpl.getAuthentication();
            UserDetailsPacking userDetailsPacking= (UserDetailsPacking) authentication.getPrincipal();
            userDetailsPacking.getUsers().setHeadImgUrl(headImgUrl);
            //3.初始化UsernamePasswordAuthenticationToken实例 ，这里的参数user就是我们要更新的用户信息
            UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetailsPacking, authentication.getCredentials());
            auth.setDetails(authentication.getDetails());
            //4.重新设置SecurityContextImpl对象的Authentication
            securityContextImpl.setAuthentication(auth);

            if (num==1){
                return R.ok();
            }else {
                return R.error(AjaxConstant.AJAX_EDIT_USERS_ERROR.getCode(),AjaxConstant.AJAX_EDIT_USERS_ERROR.getMsg());
            }
    }

    /**
     *
     */
    @PostMapping("/editUsers")
    @ResponseBody
    public R editUsers(String nickname,HttpServletRequest request){
        Users sessionUser = SecurityUtil.getSessionUser();
        Integer num =userService.editUsers(sessionUser.getId(),nickname);

        //修改redisSession中的对象
        //1.从HttpServletRequest中获取SecurityContextImpl对象
        SecurityContextImpl securityContextImpl = (SecurityContextImpl) request.getSession().getAttribute("SPRING_SECURITY_CONTEXT");
        //2.从SecurityContextImpl中获取Authentication对象
        Authentication authentication = securityContextImpl.getAuthentication();
        UserDetailsPacking userDetailsPacking= (UserDetailsPacking) authentication.getPrincipal();
        userDetailsPacking.getUsers().setNickname(nickname);
        //3.初始化UsernamePasswordAuthenticationToken实例 ，这里的参数user就是我们要更新的用户信息
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(userDetailsPacking, authentication.getCredentials());
        auth.setDetails(authentication.getDetails());
        //4.重新设置SecurityContextImpl对象的Authentication
        securityContextImpl.setAuthentication(auth);

        if (num==1){
            return R.ok();
        }else {
            return R.error(AjaxConstant.AJAX_EDIT_USERS_ERROR.getCode(),AjaxConstant.AJAX_EDIT_USERS_ERROR.getMsg());
        }

    }


}

